<template>
  <div class="blog-comment-container">
    <MessageArea @submit="handleSubmit" title="评论列表" :subTitle="`(${data.total})`" :list="data.rows" :noMore="hasMore" :isListLoading="isLoading" />
  </div>
</template>

<script>
import MessageArea from "@/components/MessageArea";
import fetchData from "@/mixins/fetchData.js";
import { rver_URL } from "@/urlConfig.js";
import {postComment, getComment} from "@/api/blog";

export default {
  mixins: [fetchData({total: 0, rows: []})],
  components: {
    MessageArea,
  },
  data() {
    return {
      page: 1,
      limit: 10,
    }
  },
  computed: {
    hasMore() {
      return this.data.rows.length < this.data.total;
    }
  },
  created() {
    this.$bus.$on("mainScroll", this.handleScroll)
  },
  destroyed() {
    this.$bus.$off("mainScroll", this.handleScroll)
  },
  methods: {
    async fetchData() {
      return await getComment(this.$route.params.id, this.page, this.limit);
    },
    imgUrl() {
      for (const item of this.data.rows) {
        item.avatar2 = rver_URL + item.avatar;
      }
    },
    async handleSubmit(formDate, callback) {
      const resp = await postComment({
        blogId: this.$route.params.id,
        ...formDate,
      });
      resp.avatar2 = rver_URL + resp.avatar;
      this.data.rows.unshift(resp);
      this.data.total++;
      callback("评论成功"); // 处理完成
    },
    // 加载下一页
    async fecthMore() {
      if(!this.hasMore) {
        return;
      }
      this.isLoading = true;
      this.page++;
      const resp = await this.fetchData();
      this.data.total = resp.total;
      this.data.rows = this.data.rows.concat(resp.rows);
      this.imgUrl();
    },
    handleScroll(dom) {
      if(this.isLoading || !dom) {
        return;
      }
      const range = 100;
      const dec = Math.abs((dom.scrollTop + dom.clientHeight) - dom.scrollHeight);
      if(dec <= range) {
        this.fecthMore()
        this.isLoading = false;
      }
    }
  }
}
</script>

<style scoped lang="less">
.blog-comment-container {
  margin: 30px 0 20px;
}
</style>